package cn.edu.nuc.zyb.frame;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import cn.edu.nuc.zyb.io.Io;
import cn.edu.nuc.zyb.model.User;

//服务器端校验数据的线程
public class UserAccept extends Thread {

	public Socket socket;
	String path = "D:\\store\\user";
	boolean flag = false;

	public UserAccept(Socket socket) {
		this.socket = socket;

	}

	// 服务器返回boolean值来确定是否登陆成功
	public void send(boolean flag) throws Exception {
		OutputStream os = socket.getOutputStream();
		DataOutputStream dos = new DataOutputStream(os);
		dos.writeBoolean(flag);

	}

	@Override
	public void run() {

		try {
			// 获取到客户端传来的数据
			InputStream in = socket.getInputStream();
			DataInputStream dis = new DataInputStream(in);
			String str = dis.readUTF();
			// 对字符串进行分割
			String[] array = str.split(",");
			String username = array[0];
			System.out.println("用户名：" + username);
			int password = Integer.valueOf(array[1]);
			System.out.println("密码：" + password);

			File file = new File(path);
			File[] files = file.listFiles();

			// 遍历文件
			for (int i = 0; i < files.length; i++) {
				// 从文件中读取
				FileInputStream fis = new FileInputStream("D:\\store\\user\\" + files[i].getName());
				ObjectInputStream ois = new ObjectInputStream(fis);
				User user = (User) ois.readObject();
				if (username.equals(user.getUsername()) && password == user.getPassword()) {
					this.flag = true;
					System.out.println("成功");
					send(flag);
				} else {
					System.out.println("失败");
					send(flag);
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
